/*
 * @Description: axios 封装
 * @Author: ShareKong
 * @Date: 2022-08-02 09:49:18
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-10-30 14:58:42
 */
import axios, { AxiosInstance, AxiosResponse, AxiosRequestConfig } from 'axios'
import { ElMessage } from 'element-plus'
import Config from './Config'
import router from '../router/index'
import { AxiosResult } from './ts-type/ts-type'

const axiosInstance: AxiosInstance = axios.create({
    baseURL: Config.apiUrl,
    timeout: Config.reqTimeout
})

// 请求错误
const requestError = (err: any): AxiosResult  => {
    console.log(err)
    ElMessage({
        message: err.message,
        type: 'error'
    })
    return {
        code: 500,
        msg: err.message,
        data: ''
    }
}

axiosInstance.interceptors.request.use((config: AxiosRequestConfig) => {
    return config
}, requestError)

axiosInstance.interceptors.response.use((response: AxiosResponse) => {
    return new Promise((resolve, reject) => {
        if(response.status == 200) {
            resolve(response.data)
        }
        else if(response.status == 401 || response.data?.code == Config.loginOutCode) {
            router.push('/login')
            reject(response.data)
        }
        else {
            reject(response.data)
        }
    })
})

const request = (method: 'get' | 'post' = 'get' ,url: string, data?: object) => {
    return new Promise<AxiosResult>((resolve, reject) => {
        resolve(axiosInstance[method](url, data))
    })
}

export default {
    async get(url: string, data?: { [key: string]: any }) {
        if(data) {
            url += '?'
            Object.keys(data).forEach(key => {
                url += `${key}=${data ? data[key] : ''}&`
            })
        }
        try {
            return await request('get', url)
        } catch (err) {
            return requestError(err)
        }
    },
    async post(url: string, data?: object) {
        try {
            return await request('post', url, data)
        } catch (err) {
            return requestError(err)
        }
    }
}